package hanelsoft.vn.dictionaylearn.control.activity;

import hanelsoft.vn.dictionaylearn.R;
import hanelsoft.vn.dictionaylearn.control.custom.CustomVocabularyContent;
import hanelsoft.vn.dictionaylearn.control.custom.CustomVocabularyContentDelete;
import hanelsoft.vn.dictionaylearn.control.service.TooltipAlarmServiceLayoutParams;
import hanelsoft.vn.dictionaylearn.control.service.TooltipRunServiceLayoutParams;
import hanelsoft.vn.dictionaylearn.control.service.WidgetStartService;
import hanelsoft.vn.dictionaylearn.model.db.DatabaseFile;
import hanelsoft.vn.dictionaylearn.model.db.DatabaseFileList;
import hanelsoft.vn.dictionaylearn.model.db.VocabularySQLiteHelper;
import hanelsoft.vn.dictionaylearn.model.entity.InfoVocabulary;
import hanelsoft.vn.dictionaylearn.model.entity.InfoVocabularyContent;
import hanelsoft.vn.dictionaylearn.model.entity.InfoVocabularyContentDelete;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class VocabularyContent extends Activity{
	ListView list;
	String name_table_vocabulary, tag = "[VocabularyContent]";
	VocabularySQLiteHelper mVocabularySQLiteHelper = new VocabularySQLiteHelper(this);
	InfoVocabularyContent info;
	InfoVocabularyContentDelete info_delete;
	ArrayList<InfoVocabularyContent> array;
	ArrayList<InfoVocabularyContentDelete>array_delete;
	private String mDBExtension;
	private String mDBPath;
	private SharedPreferences prefs;
	private DatabaseFileList mDBList;
	private DatabaseFile mDBFile;
	boolean found = false;
	Intent mIntent;
	ArrayList<InfoVocabulary> arrayVocabulary;
	SharedPreferences share, shareWidget;
	InfoVocabulary infoGetVocabulary;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		mIntent = new Intent(this, TooltipAlarmServiceLayoutParams.class);
		vocabularyContent();
	}
	private void vocabularyContent()
	{
		setContentView(R.layout.vocabulary_content);
		list = (ListView)findViewById(R.id.vocabulary_content_list);
		Intent i = this.getIntent();
		name_table_vocabulary = i.getStringExtra("name_table_vocabulary");
		list.setAdapter(new CustomVocabularyContent(VocabularyContent.this, getInfo()));
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
    			Intent i = new Intent(v.getContext(), ContentView.class);
    			info = getInfo().get(position);
    			i.putExtra("word", info.getWord());
    			i.putExtra("id",info.getId_word());
    			//get position data dictionary
    	        getPositionData();
    			i.putExtra("db", mDBFile.fileName);
    			i.putExtra("dbName",mDBFile.dictionaryName);
    			i.putExtra("style", mDBFile.style);
    			i.putExtra("sourcesound", mDBFile.sourceLanguage);
                startActivity(i);
			}
		});
	}
	private ArrayList<InfoVocabularyContent> getInfo() {
		array = mVocabularySQLiteHelper.viewAllVocabularyContent(name_table_vocabulary);
		return array;
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.content_delete, menu);
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_content_study_tooltip:
		{
			showDialogSetTime(name_table_vocabulary);
		}break;
		case R.id.menu_content_study_video:
		{
			getPositionData();
			shareWidget = getSharedPreferences("ShareWidget", 0);
			shareWidget.edit().putInt("positionStart",0).commit();
			shareWidget.edit().putString("namelist", name_table_vocabulary).commit();
			shareWidget.edit().putString("db", mDBFile.fileName).commit();
			shareWidget.edit().putString("dbName", mDBFile.dictionaryName).commit();
			shareWidget.edit().putString("style", mDBFile.style).commit();
			shareWidget.edit().putString("sourcesound", mDBFile.sourceLanguage).commit();
			shareWidget.edit().putString("soundPath", getString(R.string.soundPath)).commit();
			shareWidget.edit().putString("soundPathNotSDCard", getString(R.string.soundPathNotSDCard)).commit();
			startService(new Intent(this, WidgetStartService.class));
			Log.i(tag, "Run startService WidgetUpdateService");
			Toast.makeText(getBaseContext(), "Start Widget", Toast.LENGTH_SHORT).show();
		}break;
		case R.id.menu_content_delete:
		{
			setContentView(R.layout.vocabulary_content_delete);
			list = (ListView)findViewById(R.id.vocabulary_list_delete);
			ImageButton btnDelete = (ImageButton)findViewById(R.id.vocabulary_content_delete);
			ImageButton btnCancel = (ImageButton)findViewById(R.id.vocabulary_content_cancel);
			//
			list.setAdapter(new CustomVocabularyContentDelete(this, getInfoDelete()));
			btnDelete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					LayoutInflater mLayoutInflater = LayoutInflater.from(VocabularyContent.this);
					View mView = mLayoutInflater.inflate(R.layout.vocabulary_delete_dialog, null);
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(VocabularyContent.this);
			    	alertDialogBuilder.setView(mView);
			    	alertDialogBuilder.setTitle(R.string.delete_list_vocabulary);
			    	alertDialogBuilder.setIcon(R.drawable.delete_list);
			    	alertDialogBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {
			            @Override
			            public void onCancel(DialogInterface dialog) {
			                finish();
			            }
			        }).setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
						@SuppressLint("DefaultLocale")
						@Override
			            public void onClick(DialogInterface dialog, int which) {
							SharedPreferences share;
							share = VocabularyContent.this.getSharedPreferences("CheckDelete", 1);
							ArrayList<InfoVocabularyContentDelete>arrayDelete = array_delete;
							for(int i=0; i<list.getAdapter().getCount(); i++)
							{
								int position = share.getInt("PositionCheckItem"+i, -1);
								if(position > -1)
								{
									InfoVocabularyContentDelete infoDelte = arrayDelete.get(position);
									int id = infoDelte.getId();
									mVocabularySQLiteHelper.deleteWordVocabulary(name_table_vocabulary, id);
								}
							}
							vocabularyContent();
			            }
			        }).setNegativeButton(R.string.cancel,new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
						}
					});
			    	Dialog dialog = alertDialogBuilder.create();
			        dialog.show();
				}
			});
			btnCancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					vocabularyContent();
				}
			});
		}break;
		case R.id.menu_content_exit:
		{
			finish();
		}break;
	   }
	   return super.onOptionsItemSelected(item);
	}
	private ArrayList<InfoVocabularyContentDelete> getInfoDelete() {
		array_delete = mVocabularySQLiteHelper.viewAllDeleteVocabularyContent(name_table_vocabulary);
		return array_delete;
	}
	private void showDialogSetTime(final String nameList)
	{
		share = getSharedPreferences("Time", 1);
		LayoutInflater mLayoutInflater = LayoutInflater.from(VocabularyContent.this);
		View mView = mLayoutInflater.inflate(R.layout.layoutparams_dialog, null);
		final CheckBox cbAvailable = (CheckBox)mView.findViewById(R.id.layoutparams_dialog_runtooltip);
		final EditText time = (EditText)mView.findViewById(R.id.layoutparams_dialog_time);
		if(share.getInt("isRunService", 0) == 1)
		{
			int gettime = share.getInt("time", 0);
			time.setText(String.valueOf(gettime));
			time.setEnabled(false);
			cbAvailable.setChecked(true);
		}
		else
		{
			time.setText("");
			time.setEnabled(true);
			cbAvailable.setChecked(false);
		}
		cbAvailable.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(cbAvailable.isChecked())
				{
					if(time.getText().toString().equals(""))
					{
						cbAvailable.setChecked(false);
					}
					else
					{
						if(Integer.parseInt(time.getText().toString()) > 0)
							{
								time.setEnabled(false);
							}
						else
						{
							time.setEnabled(true);
							Toast.makeText(getBaseContext(), getString(R.string.time_is_not_available), Toast.LENGTH_SHORT).show();
						}
					}
				}
				else
				{
					time.setEnabled(true);
				}
			}
		});
		//
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(VocabularyContent.this);
		alertDialogBuilder.setView(mView);
		alertDialogBuilder.setTitle(getText(R.string.study_vocabulary_in_tooltip));
		alertDialogBuilder.setIcon(R.drawable.study_tooltip);
		alertDialogBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        }).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			@Override
            public void onClick(DialogInterface dialog, int which) {
				Log.i(tag, "Run set Service");
				if(cbAvailable.isChecked())
				{
					Log.i(tag, "cbAvailable.isChecked() = ");
					if(time.getText().toString().equals(""))
					{
						Log.i(tag, "time is null");
						cbAvailable.setChecked(false);
					}
					else
					{
						if(Integer.parseInt(time.getText().toString()) > 0)
							{
								Log.i(tag, "time > 0");
								time.setEnabled(false);
								share.edit().putInt("time", Integer.parseInt(time.getText().toString())).commit();
								Log.i(tag, "set share.edit()");
								share.edit().putInt("isRunService", 1).commit();
								share.edit().putString("namelist", nameList).commit();
								startService(mIntent);
								Log.i(tag, "startService(mIntent)");
							}
						else
						{
							Log.i(tag, "time = 0");
							time.setEnabled(true);
							Toast.makeText(getBaseContext(), getString(R.string.time_is_not_available), Toast.LENGTH_SHORT).show();
						}
					}
				}
				else
				{
					Log.i(tag, "cbAvailable.isChecked() == false");
					if(share.getInt("isRunService", 0) == 1)
					{
						share.edit().putInt("positionVocabulary", 0).commit();
						share.edit().putInt("isRunService", 0).commit();
						stopService(mIntent);
						Intent i = new Intent(VocabularyContent.this, TooltipRunServiceLayoutParams.class);
						stopService(i);
						Log.i(tag, "stop service");
					}
				}
            }
        }).setNegativeButton(R.string.cancel,new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
    	Dialog dialog = alertDialogBuilder.create();
        dialog.show();
	}
	//
	private void getPositionData() {
		mDBExtension = getResources().getString(R.string.dbExtension);
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        	mDBPath = getResources().getString(R.string.dbPath);
        }
        else
        {
        	mDBPath = getResources().getString(R.string.dbPathNotSDCard);
        }
        //mDBPath = getResources().getString(R.string.dbPath);
        mDBList = new DatabaseFileList(mDBPath,mDBExtension);
        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String savedDB = prefs.getString("defaultDictionary", ""); //Default dictionary is the first dictionary in the list
		String savedDBPath = prefs.getString("defaultDictionaryPath", ""); //Default dictionary is the first dictionary in the list
		if (savedDB.trim().equals("") || savedDBPath.trim().equals(""))
		{
			if (mDBList != null && mDBList.items.size() > 0)
			{
				mDBFile = mDBList.items.get(0);
			}
			else
			{
				mDBFile = null;
			}
		}
		else
		{
			if (mDBList != null && mDBList.items.size() > 0)
			{
				for (DatabaseFile d : mDBList.items)
				{
					if (d.fileName.equals(savedDB) && d.path.equals(savedDBPath))
					{
						mDBFile = d;
						found = true;
						break;
					}
				}
				if (!found)
				{
					mDBFile = mDBList.items.get(0);
				}
			}
			else
			{
				mDBFile = null;
			}
		}
	}
}
